/**
 * 
 */
package com.rio.dandan.util;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Component;

import com.rio.dandan.bean.UserBean;
import com.rio.dandan.exception.AccountNotFoundException;
import com.rio.dandan.pojo.UserAccount;
import com.rio.dandan.pojo.UserProfile;
import com.rio.dandan.service.UserAccountService;
import com.rio.dandan.service.UserProfileService;

/**
 * 
 * SecurityUtils.java
 * 
 * @author 宋陆
 * @version 1.0 2014年5月20日
 */
@Component
public class SecurityUtils extends org.apache.shiro.SecurityUtils {

    public static UserAccountService userAccountService;
    public static UserProfileService userProfileService;

    public static void login(String username, String password, boolean isRememberMe) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, isRememberMe);
        try {
            getSubject().login(token);
            String uid = getCurrUId();
            if (uid != null) {
                UserAccount userAccount = userAccountService.getUserAccount(uid);
                UserProfile userProfile = userProfileService.getUserProfile(uid);
                UserBean userBean = new UserBean();
                userBean.setUid(uid);
                userBean.setUsername(userAccount.getUsername());
                userBean.setRealname(userProfile.getRealname());
                userBean.setGender(userProfile.getGender());
                userBean.setGradeStatus(userAccount.getGrade());
                SessionUtils.getSession().setAttribute("currUser", userBean);
            }
        } catch (AuthenticationException ex) {
            throw new AccountNotFoundException("ex.authentication");
        }
    }

    public static void logout() {
        getSubject().logout();
    }

    public static String getCurrUId() {
        return (String) getSubject().getPrincipal();
    }

    @Resource(type = UserAccountService.class)
    public void setUserAccountService(UserAccountService userAccountService) {
        SecurityUtils.userAccountService = userAccountService;
    }

    @Resource(type = UserProfileService.class)
    public void setUserProfileService(UserProfileService userProfileService) {
        SecurityUtils.userProfileService = userProfileService;
    }
}
